'''
Created on Jul 5, 2010

@author: Behrooz Nobakht
'''
from django.db import models
from amscms import settings
from amscms.ams.managers import TimePeriod
import datetime

class TermManager(models.Manager):
    
    def find_or_create(self, term, lang_code=settings.LANGUAGE_CODE):
        from amscms.dict.models import Term
        from amscms.dict.models import Language
        lang = None
        try:
            lang = Language.objects.get(code=lang_code)
        except:
            return
        if lang is None:
            return
        the_term, created = Term.objects.get_or_create(term=term, language=lang)
        if not created and the_term is None:
            return None
        return the_term
    
    def find_or_create_search_term(self, term, lang_code=settings.LANGUAGE_CODE):
        the_term = self.find_or_create(term, lang_code)
        if the_term is None:
            return None
        if the_term.frequency > 0:
            return the_term
        the_term.save()
        return the_term
    
    def find_popular_terms(self, size=15, period=None):
        from amscms.dict.models import Term
        if period is None:
            terms = Term.objects.exclude(enabled=False).order_by('-frequency')[0:size]
            return terms
        if period == TimePeriod.WEEK:
            end = datetime.date.today()
            start = end - datetime.timedelta(days=7)
        elif period == TimePeriod.MONTH:
            end = datetime.date.today()
            start = end - datetime.timedelta(days=30)
        elif period == TimePeriod.YEAR:
            end = datetime.date.today()
            start = end - datetime.timedelta(days=365)
        terms = Term.objects.exclude(enabled=False).\
                filter(adtag__last_modified__range=(start, end)).distinct().\
                order_by("-frequency")[0:size]
        return terms
    
    def create_terms(self, words):
        from amscms.dict.models import Term
        terms = []
        for w in words:
            if len(w) > 1:
                terms.append(Term(term=w))
        return terms
    
    def prepare_importance_cloud(self, terms):
        from math import fabs, floor
        dict = []
        for t in terms:
            importance = int(floor(fabs(t.frequency - 70) / (150 - 70)) + 90)
            dict.append({'term': t.term, 'frequency' : t.frequency, 'importance':  importance, 'id': t.id})
        return dict
        